import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/api/index.dart';
import '../../../common/mixins/user_profile_mixin.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/utils/system_ui_utils.dart';
import '../../../common/services/alipay_service.dart';

/// 积分资金页面控制器
class FundsController extends GetxController with UserProfileMixin {
  FundsController();

  // ==================== 响应式状态 ====================
  
  /// 积分套餐列表
  final pointsPackages = <PointsPackageModel>[].obs;
  
  /// 积分变更历史
  final pointsHistory = <PointsHistoryModel>[].obs;
  
  /// 加载状态
  final isLoading = false.obs;
  final isLoadingPackages = false.obs;
  final isLoadingHistory = false.obs;
  
  /// 错误信息
  final errorMessage = ''.obs;
  
  /// 当前页码
  final currentPage = 1.obs;
  
  /// 是否还有更多数据
  final hasMore = true.obs;
  
  /// 选中的套餐
  final Rx<PointsPackageModel?> selectedPackage = Rx<PointsPackageModel?>(null);

  // ==================== 计算属性 ====================
  
  /// 用户当前积分
  int get userPoints => currentUserProfile?.userPoints ?? 0;
  
  /// 用户等级进度
  LevelProgress get levelProgress => LevelUtil.getLevelProgress(userPoints);
  
  /// 用户等级名称
  String get userLevelName => levelProgress.currentLevelName;
  
  /// 等级显示文本
  String get levelDisplayText => 'Lv${levelProgress.currentLevel}';
  
  /// 升级所需积分
  int get pointsToNextLevel => levelProgress.pointsToNext;
  
  /// 等级进度百分比
  double get levelProgressPercent => levelProgress.progress / 100.0;

  // ==================== 初始化 ====================
  
  _initData() async {
    isLoading.value = true;
    errorMessage.value = '';
    
    try {
      // 并行加载套餐列表和历史记录
      await Future.wait([
        loadPointsPackages(),
        loadPointsHistory(refresh: true),
      ]);
    } catch (e) {
      debugPrint('❌ 初始化积分页面失败: $e');
      errorMessage.value = '加载失败，请稍后重试';
    } finally {
      isLoading.value = false;
      update(["funds"]);
    }
  }

  // ==================== 数据加载方法 ====================
  
  /// 加载积分套餐列表
  Future<void> loadPointsPackages() async {
    try {
      isLoadingPackages.value = true;
      debugPrint('📦 开始加载积分套餐列表...');
      
      final response = await PointsApi.getPointsPackages();
      
      if (response.status == 'success') {
        pointsPackages.value = response.packages;
        debugPrint('✅ 积分套餐加载成功，共 ${response.packages.length} 个套餐');
      } else {
        debugPrint('❌ 积分套餐加载失败: ${response.message}');
        Get.snackbar('提示', response.message);
      }
    } catch (e) {
      debugPrint('❌ 加载积分套餐异常: $e');
      Get.snackbar('错误', '加载套餐列表失败');
    } finally {
      isLoadingPackages.value = false;
    }
  }
  
  /// 加载积分变更历史
  Future<void> loadPointsHistory({bool refresh = false}) async {
    try {
      if (refresh) {
        currentPage.value = 1;
        hasMore.value = true;
      }
      
      if (!hasMore.value) {
        debugPrint('⚠️ 没有更多数据了');
        return;
      }
      
      isLoadingHistory.value = true;
      debugPrint('📜 开始加载积分历史，页码: ${currentPage.value}');
      
      final response = await PointsApi.getPointsHistory(
        userId: userId,
        page: currentPage.value,
        pageSize: 20,
      );
      
      if (response.status == 'success') {
        if (refresh) {
          pointsHistory.value = response.history;
        } else {
          pointsHistory.addAll(response.history);
        }
        
        // 判断是否还有更多数据
        if (response.history.isEmpty || response.history.length < 20) {
          hasMore.value = false;
        } else {
          currentPage.value++;
        }
        
        debugPrint('✅ 积分历史加载成功，当前共 ${pointsHistory.length} 条记录');
      } else {
        debugPrint('❌ 积分历史加载失败: ${response.message}');
        Get.snackbar('提示', response.message);
      }
    } catch (e) {
      debugPrint('❌ 加载积分历史异常: $e');
      Get.snackbar('错误', '加载历史记录失败');
    } finally {
      isLoadingHistory.value = false;
    }
  }
  
  /// 刷新数据
  Future<void> refreshData() async {
    debugPrint('🔄 刷新积分页面数据');
    await _initData();
  }
  
  /// 加载更多历史记录
  Future<void> loadMoreHistory() async {
    if (!isLoadingHistory.value && hasMore.value) {
      await loadPointsHistory(refresh: false);
    }
  }

  // ==================== 业务方法 ====================
  
  /// 选择套餐
  void selectPackage(PointsPackageModel package) {
    selectedPackage.value = package;
    debugPrint('✅ 已选择套餐: ${package.name} - ¥${package.price}');
    update(["funds"]);
  }
  
  /// 取消选择
  void clearSelection() {
    selectedPackage.value = null;
    update(["funds"]);
  }
  
  /// 购买积分套餐
  Future<void> goToPayment() async {
    if (selectedPackage.value == null) {
      Get.snackbar('提示', '请先选择积分套餐');
      return;
    }
    
    final package = selectedPackage.value!;
    
    try {
      debugPrint('🔄 开始购买积分套餐: ${package.name}');
      
      // 检查是否安装了支付宝
      final isAlipayInstalled = await AlipayService.to.isInstalled();
      if (!isAlipayInstalled) {
        Get.snackbar('提示', '请先安装支付宝客户端');
        return;
      }
      
      Get.snackbar('提示', '正在创建支付订单...', duration: const Duration(seconds: 1));
      
      // 创建支付宝订单
      final response = await PointsApi.createAlipayOrder(
        userId: userId,
        packageId: package.id,
      );
      
      if (response['status'] == 'success') {
        debugPrint('✅ 支付订单创建成功');
        
        // 获取支付宝订单字符串
        final orderString = response['alipay_order_string'];
        
        if (orderString != null && orderString.isNotEmpty) {
          // 调起支付宝支付
          if (AlipayService.to.isIOSSimulator) {
            Get.snackbar('提示', 'iOS模拟器环境，将显示模拟支付对话框...', duration: const Duration(seconds: 1));
          } else {
            Get.snackbar('提示', '正在跳转至支付宝...', duration: const Duration(seconds: 1));
          }
          
          final payResult = await AlipayService.to.pay(orderString);
          
          if (payResult != null) {
            await _handlePaymentResult(payResult, package);
          } else {
            Get.snackbar('错误', '支付失败，请重试');
          }
        } else {
          Get.snackbar('错误', '支付订单信息异常');
        }
      } else {
        debugPrint('❌ 支付订单创建失败: ${response['message']}');
        Get.snackbar('错误', '创建支付订单失败: ${response['message']}');
      }
    } catch (e) {
      debugPrint('💥 购买积分套餐异常: $e');
      Get.snackbar('错误', '购买失败，请稍后再试');
    }
  }
  
  /// 处理支付结果
  Future<void> _handlePaymentResult(Map<String, dynamic> result, PointsPackageModel package) async {
    final resultStatus = result['resultStatus'];
    switch (resultStatus) {
      case '9000':
        // 支付成功
        Get.snackbar('成功', '支付成功！积分将在稍后到账', backgroundColor: Colors.green[100]);
        // 刷新用户积分和积分变更历史
        await refreshData();
        // 重置选择
        clearSelection();
        break;
        
      case '8000':
        // 支付正在处理中
        Get.snackbar('提示', '支付正在处理中，请稍候查看积分变化');
        await refreshData();
        break;
        
      case '4000':
        // 订单支付失败
        Get.snackbar('失败', '支付失败，请重试', backgroundColor: Colors.red[100]);
        break;
        
      case '5000':
        // 重复请求
        Get.snackbar('提示', '请不要重复支付');
        break;
        
      case '6001':
        // 用户中途取消
        Get.snackbar('提示', '支付已取消');
        break;
        
      case '6002':
        // 网络连接出错
        Get.snackbar('错误', '网络连接异常，请检查网络后重试');
        break;
        
      default:
        Get.snackbar('错误', '支付异常，请联系客服');
        debugPrint('未知支付状态: $resultStatus');
    }
  }
  
  /// 删除历史记录（如果支持）
  void deleteHistoryItem(PointsHistoryModel item) {
    // TODO: 调用删除API
    pointsHistory.remove(item);
    update(["funds"]);
  }

  // ==================== 生命周期 ====================

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
  
  @override
  void onClose() {
    // 🔄 恢复默认状态栏样式（浅色背景用深色图标）
    SystemUIUtils.setTransparentStatusBarDark();
    super.onClose();
  }
}
